<template>
  <el-dialog
    v-model="dialogVisible"
    title="制度分析"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="system-analysis">
      <!-- 分析条件 -->
      <el-card class="analysis-conditions" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">分析条件</span>
            <div class="header-actions">
              <el-button type="primary" size="small" @click="handleAnalyze">
                <el-icon><TrendCharts /></el-icon>
                开始分析
              </el-button>
              <el-button size="small" @click="handleExportReport">
                <el-icon><Download /></el-icon>
                导出报告
              </el-button>
            </div>
          </div>
        </template>

        <el-form :model="analysisForm" label-width="100px" :inline="true">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="analysisForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="制度类型">
            <el-select v-model="analysisForm.systemType" placeholder="全部类型" clearable style="width: 150px">
              <el-option label="管理制度" value="management" />
              <el-option label="操作规程" value="operation" />
              <el-option label="技术标准" value="technical" />
              <el-option label="安全规范" value="safety" />
              <el-option label="质量标准" value="quality" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门">
            <el-select v-model="analysisForm.department" placeholder="全部部门" clearable style="width: 150px">
              <el-option label="管理部" value="management" />
              <el-option label="技术部" value="technical" />
              <el-option label="安全部" value="safety" />
              <el-option label="质量部" value="quality" />
            </el-select>
          </el-form-item>
          <el-form-item label="分析维度">
            <el-select v-model="analysisForm.dimension" placeholder="请选择" style="width: 150px">
              <el-option label="按类型" value="type" />
              <el-option label="按部门" value="department" />
              <el-option label="按状态" value="status" />
              <el-option label="按时间" value="time" />
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 统计概览 -->
      <el-card class="statistics-overview" shadow="never">
        <template #header>
          <span class="card-title">统计概览</span>
        </template>

        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ overviewData.total }}</div>
              <div class="stat-label">制度总数</div>
              <div class="stat-trend positive">
                <el-icon><TrendCharts /></el-icon>
                +{{ overviewData.totalTrend }}%
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ overviewData.active }}</div>
              <div class="stat-label">生效制度</div>
              <div class="stat-trend positive">
                <el-icon><TrendCharts /></el-icon>
                +{{ overviewData.activeTrend }}%
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ overviewData.updated }}</div>
              <div class="stat-label">本月更新</div>
              <div class="stat-trend negative">
                <el-icon><TrendCharts /></el-icon>
                {{ overviewData.updatedTrend }}%
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ overviewData.compliance }}%</div>
              <div class="stat-label">合规率</div>
              <div class="stat-trend positive">
                <el-icon><TrendCharts /></el-icon>
                +{{ overviewData.complianceTrend }}%
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 图表分析 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">制度分布统计</span>
                <el-select v-model="chartType" size="small" style="width: 120px">
                  <el-option label="饼图" value="pie" />
                  <el-option label="柱状图" value="bar" />
                </el-select>
              </div>
            </template>
            <div ref="distributionChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <span class="card-title">制度趋势分析</span>
            </template>
            <div ref="trendChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <span class="card-title">部门制度对比</span>
            </template>
            <div ref="departmentChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <span class="card-title">制度状态分析</span>
            </template>
            <div ref="statusChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据 -->
      <el-card class="detail-data" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">详细数据</span>
            <div class="header-actions">
              <el-select v-model="tableGroupBy" size="small" style="width: 120px; margin-right: 10px">
                <el-option label="按类型" value="type" />
                <el-option label="按部门" value="department" />
                <el-option label="按状态" value="status" />
              </el-select>
              <el-button size="small" @click="handleExportTable">
                <el-icon><Download /></el-icon>
                导出数据
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="tableLoading"
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column :prop="getTableColumnProp()" :label="getTableColumnLabel()" width="150" />
          <el-table-column prop="total" label="总数" width="100" />
          <el-table-column prop="active" label="生效" width="100" />
          <el-table-column prop="draft" label="草稿" width="100" />
          <el-table-column prop="expired" label="过期" width="100" />
          <el-table-column prop="abolished" label="废止" width="100" />
          <el-table-column prop="compliance" label="合规率" width="100">
            <template #default="{ row }">
              <span :class="getComplianceClass(row.compliance)">
                {{ row.compliance }}%
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="lastUpdate" label="最近更新" width="120" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" link @click="handleViewDetail(row)">
                查看详情
              </el-button>
              <el-button type="success" size="small" link @click="handleViewTrend(row)">
                查看趋势
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  TrendCharts,
  Download
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// Props
interface Props {
  visible: boolean
}

const props = withDefaults(defineProps<Props>(), {})

// Emits
const emit = defineEmits(['update:visible'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 分析表单
const analysisForm = reactive({
  dateRange: [],
  systemType: '',
  department: '',
  dimension: 'type'
})

// 统计概览数据
const overviewData = ref({
  total: 156,
  totalTrend: 12.5,
  active: 142,
  activeTrend: 8.3,
  updated: 23,
  updatedTrend: -5.2,
  compliance: 95.8,
  complianceTrend: 2.1
})

// 图表类型
const chartType = ref('pie')

// 表格分组方式
const tableGroupBy = ref('type')

// 表格数据
const tableData = ref([
  {
    type: '管理制度',
    department: '管理部',
    status: '生效',
    total: 45,
    active: 42,
    draft: 2,
    expired: 1,
    abolished: 0,
    compliance: 95.6,
    lastUpdate: '2024-01-15'
  },
  {
    type: '操作规程',
    department: '技术部',
    status: '生效',
    total: 38,
    active: 35,
    draft: 1,
    expired: 2,
    abolished: 0,
    compliance: 92.1,
    lastUpdate: '2024-01-10'
  },
  {
    type: '技术标准',
    department: '技术部',
    status: '生效',
    total: 32,
    active: 30,
    draft: 1,
    expired: 1,
    abolished: 0,
    compliance: 96.9,
    lastUpdate: '2024-01-12'
  },
  {
    type: '安全规范',
    department: '安全部',
    status: '生效',
    total: 28,
    active: 26,
    draft: 1,
    expired: 1,
    abolished: 0,
    compliance: 98.2,
    lastUpdate: '2024-01-08'
  },
  {
    type: '质量标准',
    department: '质量部',
    status: '生效',
    total: 13,
    active: 9,
    draft: 2,
    expired: 2,
    abolished: 0,
    compliance: 89.7,
    lastUpdate: '2024-01-05'
  }
])

// 表格加载状态
const tableLoading = ref(false)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 5
})

// 图表引用
const distributionChartRef = ref()
const trendChartRef = ref()
const departmentChartRef = ref()
const statusChartRef = ref()

// 图表实例
let distributionChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null
let departmentChart: echarts.ECharts | null = null
let statusChart: echarts.ECharts | null = null

// 获取表格列属性
const getTableColumnProp = () => {
  const props: Record<string, string> = {
    type: 'type',
    department: 'department',
    status: 'status'
  }
  return props[tableGroupBy.value] || 'type'
}

// 获取表格列标签
const getTableColumnLabel = () => {
  const labels: Record<string, string> = {
    type: '制度类型',
    department: '所属部门',
    status: '制度状态'
  }
  return labels[tableGroupBy.value] || '制度类型'
}

// 获取合规率样式
const getComplianceClass = (compliance: number) => {
  if (compliance >= 95) return 'compliance-high'
  if (compliance >= 90) return 'compliance-medium'
  return 'compliance-low'
}

// 表格汇总方法
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item: any) => Number(item[column.property]))
    if (!values.every((value: number) => Number.isNaN(value))) {
      if (column.property === 'compliance') {
        sums[index] = (values.reduce((prev: number, curr: number) => prev + curr, 0) / values.length).toFixed(1) + '%'
      } else {
        sums[index] = values.reduce((prev: number, curr: number) => prev + curr, 0).toString()
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    initDistributionChart()
    initTrendChart()
    initDepartmentChart()
    initStatusChart()
  })
}

// 初始化分布统计图表
const initDistributionChart = () => {
  if (!distributionChartRef.value) return
  
  distributionChart = echarts.init(distributionChartRef.value)
  updateDistributionChart()
}

// 更新分布统计图表
const updateDistributionChart = () => {
  if (!distributionChart) return

  const data = [
    { name: '管理制度', value: 45 },
    { name: '操作规程', value: 38 },
    { name: '技术标准', value: 32 },
    { name: '安全规范', value: 28 },
    { name: '质量标准', value: 13 }
  ]

  const option = chartType.value === 'pie' ? {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '制度分布',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  } : {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '制度数量',
        type: 'bar',
        data: data.map(item => item.value),
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }

  distributionChart.setOption(option)
}

// 初始化趋势分析图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['新增制度', '更新制度', '废止制度']
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增制度',
        type: 'line',
        data: [5, 8, 12, 6, 9, 15],
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '更新制度',
        type: 'line',
        data: [12, 15, 18, 22, 16, 20],
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '废止制度',
        type: 'line',
        data: [2, 1, 3, 2, 1, 2],
        itemStyle: { color: '#F56C6C' }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化部门对比图表
const initDepartmentChart = () => {
  if (!departmentChartRef.value) return
  
  departmentChart = echarts.init(departmentChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['制度总数', '生效制度']
    },
    xAxis: {
      type: 'category',
      data: ['管理部', '技术部', '安全部', '质量部']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '制度总数',
        type: 'bar',
        data: [45, 70, 28, 13],
        itemStyle: { color: '#909399' }
      },
      {
        name: '生效制度',
        type: 'bar',
        data: [42, 65, 26, 9],
        itemStyle: { color: '#67C23A' }
      }
    ]
  }
  
  departmentChart.setOption(option)
}

// 初始化状态分析图表
const initStatusChart = () => {
  if (!statusChartRef.value) return
  
  statusChart = echarts.init(statusChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '制度状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        data: [
          { value: 142, name: '生效中', itemStyle: { color: '#67C23A' } },
          { value: 7, name: '草稿', itemStyle: { color: '#909399' } },
          { value: 5, name: '已过期', itemStyle: { color: '#E6A23C' } },
          { value: 2, name: '已废止', itemStyle: { color: '#F56C6C' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  statusChart.setOption(option)
}

// 开始分析
const handleAnalyze = () => {
  tableLoading.value = true
  setTimeout(() => {
    tableLoading.value = false
    ElMessage.success('分析完成')
  }, 1500)
}

// 导出报告
const handleExportReport = () => {
  ElMessage.success('分析报告导出成功')
}

// 导出表格数据
const handleExportTable = () => {
  ElMessage.success('数据导出成功')
}

// 查看详情
const handleViewDetail = (row: any) => {
  ElMessage.info(`查看 ${row[getTableColumnProp()]} 的详细信息`)
}

// 查看趋势
const handleViewTrend = (row: any) => {
  ElMessage.info(`查看 ${row[getTableColumnProp()]} 的趋势分析`)
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  handleAnalyze()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  handleAnalyze()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 监听图表类型变化
watch(chartType, () => {
  updateDistributionChart()
})

// 监听表格分组变化
watch(tableGroupBy, () => {
  handleAnalyze()
})

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    initCharts()
  }
})

// 组件挂载
onMounted(() => {
  if (dialogVisible.value) {
    initCharts()
  }
})

// 组件卸载
onUnmounted(() => {
  if (distributionChart) {
    distributionChart.dispose()
    distributionChart = null
  }
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  if (departmentChart) {
    departmentChart.dispose()
    departmentChart = null
  }
  if (statusChart) {
    statusChart.dispose()
    statusChart = null
  }
})
</script>

<style scoped>
.system-analysis {
  max-height: 80vh;
  overflow-y: auto;
}

.analysis-conditions,
.statistics-overview,
.chart-card,
.detail-data {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
}

.analysis-conditions:last-child,
.statistics-overview:last-child,
.chart-card:last-child,
.detail-data:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  position: relative;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.stat-trend.positive {
  color: #67c23a;
}

.stat-trend.negative {
  color: #f56c6c;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.compliance-high {
  color: #67c23a;
  font-weight: 600;
}

.compliance-medium {
  color: #e6a23c;
  font-weight: 600;
}

.compliance-low {
  color: #f56c6c;
  font-weight: 600;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 15px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}
</style>